package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomId;
import br.com.telescope.adsrt.dom.DomLogin;
import br.com.telescope.adsrt.dom.DomPasswordHash;
import br.com.telescope.adsrt.dom.DomProperties;
import br.com.telescope.adsrt.dom.DomTextLong;
import br.com.telescope.adsrt.dom.DomUpper;
import br.com.telescope.adsrt.dom.DomUrl;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.t2.AccessPolicy;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.exception.UnexpectedException;
import br.com.telescope.t2.feature.CustomActionFeature;
import br.com.telescope.t2.feature.DeleteFeature;
import br.com.telescope.t2.feature.InsertFeature;
import br.com.telescope.t2.feature.ListFeature;
import br.com.telescope.t2.feature.QueryFeature;
import br.com.telescope.t2.feature.SearchFeature;
import br.com.telescope.t2.feature.UpdateFeature;
import br.com.telescope.t2.feature.ViewFeature;
import br.com.telescope.util.HttpRequester;
import java.util.List;
import solutions.ferpa.ztest.ent.*;

/**
 * Tokens.
 * <p>
 * Permite consultar e cadastrar tokens de acesso ao sistema.
 * <P>
 * Telescope origin: RTAUTH_UTIL.CAD_TOKENS
 * <P>
 * Base entity: RTPREF.PREFERENCIAS
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class CadTokens extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTAUTH_UTIL.CAD_TOKENS";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Tokens");
    }
    
    protected EntPreferencias base;
    protected EntPreferencias rec; // NEED_TJW1_COMPATIBILITY
    
    // Record items
    private DomProperties aValor;
    private DomTextLong aDescricao;
    private DomUpper aPreferencia;
    private DomUrl aUrlServidorEligo;
    private DomLogin aUsuarioEligo;
    private DomPasswordHash aSenha;
    private DomUpper aToken;
    private DomId aId;
    
    // Query items
    private DomTextLong qDescricao;
    private DomProperties qValor;
    private DomUpper qToken;
    
    @Override
    public String getBaseSql() {
        return "select BASE.*"
                + " , (substr(base.preferencia,10,99)) as TOKEN"
                + " from PREFERENCIAS BASE";
    }
    
    @Override
    public String getBaseSqlWhereClause() {
        
        return " where base.preferencia like 'RT.TOKEN.%'";
    }
    
    @Override
    public void initAttributes() {
        
        aValor = new DomProperties();
        aValor.context(ctx).name("VALOR").label("Valor").width(60);
        
        aDescricao = new DomTextLong();
        aDescricao.context(ctx).name("DESCRICAO").label("Descrição").width(60).height(2);
        aDescricao.setDefaultValue("Inserido automaticamente!");
        
        aPreferencia = new DomUpper();
        aPreferencia.context(ctx).name("PREFERENCIA").label("Preferência").width(60);
        
        aUrlServidorEligo = new DomUrl();
        aUrlServidorEligo.context(ctx).name("URL_SERVIDOR_ELIGO").label("URL do servidor Eligo").unbound(true);
        
        aUsuarioEligo = new DomLogin();
        aUsuarioEligo.context(ctx).name("USUARIO_ELIGO").label("Usuário eligo").unbound(true);
        
        aSenha = new DomPasswordHash();
        aSenha.context(ctx).name("SENHA").label("Senha").unbound(true);
        
        aToken = new DomUpper();
        aToken.context(ctx).name("TOKEN").label("Token").width(40).unbound(true).sqlExpression(true);
        
        aId = new DomId();
        aId.context(ctx).name("ID").label("ID");
        
        
        qDescricao = new DomTextLong();
        qDescricao.context(ctx).name("DESCRICAO").label("Descrição");
        
        qValor = new DomProperties();
        qValor.context(ctx).name("VALOR").label("Valor");
        
        qToken = new DomUpper();
        qToken.context(ctx).name("TOKEN").label("Token");
    }
    
    @Override
    public String getQueryPkColumn() {
        return "BASE.ID";
    }
    
    @Override
    public void setId(String value) {
        this.aId.setValue(value);
    }
    
    @Override
    public EntPreferencias getRecord() {
        if (base == null) {
            base = new EntPreferencias(ctx);
            rec = base;
        }
        return this.base;
    }
    
    @Override
    public String getContextName() {
        return aToken.toText();
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "TOKEN, VALOR, DESCRICAO";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="QUERY">
    public class FQuery extends QueryFeature {
        
        @Override
        public void initForm() {
            addField(qToken, "opt");
            addField(qValor, "opt");
            addField(qDescricao, "opt");
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("CREATE")).label("Criar token");
        }
        
        {
            setFeatureName("QUERY");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="SEARCH">
    public class FSearch extends SearchFeature {
        
        @Override
        public void initForm() {
            addField(qToken, "search");
            addField(qValor, "search");
            addField(qDescricao, "search");
        }
        
        {
            setFeatureName("SEARCH");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="LIST">
    public class FList extends ListFeature {
        
        @Override
        public void initForm() {
            addField(aToken, "view");
            addField(aValor, "view");
            addField(aDescricao, "view");
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("CREATE")).label("Criar token");
        }
        
        {
            setFeatureName("LIST");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="INSERT">
    public class FInsert extends InsertFeature {
        
        @Override
        public void initForm() {
            aToken.setOptional(false);
            addField(aToken, "rqd");
            aValor.setOptional(false);
            addField(aValor, "rqd");
            addField(aDescricao, "opt");
        }
        
        @Override
        public void preInsert() {
            try {
                calcularNomePreferencia();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("INSERT");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="VIEW">
    public class FView extends ViewFeature {
        
        @Override
        public void initForm() {
            addField(aToken, "view");
            addField(aValor, "view");
            addField(aDescricao, "view");
        }
        
        {
            setFeatureName("VIEW");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="UPDATE">
    public class FUpdate extends UpdateFeature {
        
        @Override
        public void initForm() {
            aToken.setOptional(false);
            addField(aToken, "rqd");
            aValor.setOptional(false);
            addField(aValor, "rqd");
            addField(aDescricao, "opt");
        }
        
        @Override
        public void preUpdate() {
            try {
                calcularNomePreferencia();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("UPDATE");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CREATE">
    public class FCreate extends CustomActionFeature {
        
        @Override
        public void initForm() {
            aToken.setOptional(false);
            addField(aToken, "rqd");
            aUrlServidorEligo.setOptional(false);
            addField(aUrlServidorEligo, "rqd");
            aUsuarioEligo.setOptional(false);
            addField(aUsuarioEligo, "rqd");
            aSenha.setOptional(false);
            addField(aSenha, "rqd");
        }
        
        @Override
        public int getAccessPolicy() {
            return AccessPolicy.USER;
        }
        
        @Override
        public void onAction() {
            
        }
        
        @Override
        public void execute() {
            try {
                create();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("CREATE");
            setTitle("Criar token");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="DELETE">
    public class FDelete extends DeleteFeature {
        
        @Override
        public void initForm() {
            addField(aToken, "view");
        }
        
        {
            setFeatureName("DELETE");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FQuery());
        addFeature(new FSearch());
        addFeature(new FList());
        addFeature(new FInsert());
        addFeature(new FView());
        addFeature(new FUpdate());
        addFeature(new FCreate());
        addFeature(new FDelete());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "QUERY";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public String getValor() {
        return aValor.getValue();
    }
    
    public void setValor(String value) {
        this.aValor.setValue(value);
    }
    
    public String getDescricao() {
        return aDescricao.getValue();
    }
    
    public void setDescricao(String value) {
        this.aDescricao.setValue(value);
    }
    
    public String getPreferencia() {
        return aPreferencia.getValue();
    }
    
    public void setPreferencia(String value) {
        this.aPreferencia.setValue(value);
    }
    
    public String getUrlServidorEligo() {
        return aUrlServidorEligo.getValue();
    }
    
    public void setUrlServidorEligo(String value) {
        this.aUrlServidorEligo.setValue(value);
    }
    
    public String getUsuarioEligo() {
        return aUsuarioEligo.getValue();
    }
    
    public void setUsuarioEligo(String value) {
        this.aUsuarioEligo.setValue(value);
    }
    
    public String getSenha() {
        return aSenha.getValue();
    }
    
    public void setSenha(String value) {
        this.aSenha.setValue(value);
    }
    
    public String getToken() {
        return aToken.getValue();
    }
    
    public void setToken(String value) {
        this.aToken.setValue(value);
    }
    
    @Override
    public Long getId() {
        return aId.getValue();
    }
    
    public void setId(Long value) {
        this.aId.setValue(value);
    }
    public String getQueryToken() {
        return qToken.getQueryValue();
    }
    
    public void setQueryToken(String value) {
        this.qToken.setQueryValue(value);
    }
    public String getQueryValor() {
        return qValor.getQueryValue();
    }
    
    public void setQueryValor(String value) {
        this.qValor.setQueryValue(value);
    }
    public String getQueryDescricao() {
        return qDescricao.getQueryValue();
    }
    
    public void setQueryDescricao(String value) {
        this.qDescricao.setQueryValue(value);
    }
    // </editor-fold>
    
    /**
     * Calcular o nome da preferencia.
     */
    public void calcularNomePreferencia() throws AdsException {
        // <user-code id="6262507" parentId="6262504" hashcode="23fd43c8" length="52">
        rec.setPreferencia("RT.TOKEN." + aToken.getValue());
        // </user-code>
    }
    
    /**
     * Criar token.
     * <p>
     * Permite informar a URL e as credenciais de acesso.
     */
    public void create() throws AdsException {
        // <user-code id="21583626" parentId="21583620" hashcode="-6642a25" length="1078">
        // import br.com.telescope.util.HttpRequester;
        // import br.com.telescope.t2.exception.UnexpectedException;
        ctx.readFields(aUrlServidorEligo, aUsuarioEligo, aSenha, aToken);
        String nome = aToken.getValue();
        ctx.setPreference("RT.TOKEN." + nome + "_URL", aUrlServidorEligo.getValue());
        List<String> response = new HttpRequester()
                .baseUrl(aUrlServidorEligo.getValue())
                .parm("P_LOGIN", aUsuarioEligo.getValue())
                .parm("P_PASSWORD", aSenha.getValue())
                .post("app/UtlCreateToken")
                .getResponse();
        if (response == null) {
            throw new UnexpectedException("Não foi possível obter resposta do servidor!");
        }
        if (response.size() != 2) {
            for (String line : response) {
                ctx.p("<br>" + line);
            }
            throw new UnexpectedException("Não foi possível interpretar resposta do servidor!");
        }
        if (response.get(0).equals("OK")) {
            ctx.setPreference("RT.TOKEN." + nome, response.get(1));
            ctx.showSuccess("Token criado com sucesso!");
        } else {
            throw new UnexpectedException(response.get(1));
        }
        doIndex();
        // </user-code>
    }
}
